package com.service.business.member.controller;

import com.service.business.base.dto.LoginUserSession;
import com.service.business.base.enums.SmsTypeEnum;
import com.service.business.framework.log.RequestLog;
import com.service.business.member.controller.rep.MemberStorePageRep;
import com.service.business.member.controller.req.MemberWithdrawReq;
import com.service.business.member.controller.req.TransferAccountReq;
import com.service.business.member.controller.req.TwoFaReq;
import com.service.business.member.enums.MemberEnums;
import com.service.business.member.service.MemberCapitalMeasurementService;
import com.service.business.member.service.MemberService;
import com.service.business.member.service.MemberStoreService;
import com.service.business.support.MemberStoreLockUtils;
import com.service.business.support.SessionUtil;
import com.service.business.support.VerifyCodeUtil;
import com.service.business.support.WxMsgUtil;
import com.service.core.exception.CommonException;
import com.service.core.rest.BaseController;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.MultiResponse;
import com.service.dao.enums.CoinsEnum;
import com.service.dao.model.Member;
import com.service.dao.model.MemberStore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonRedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年09月24日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@RestController()
@RequestMapping("member-store")
@Api(tags = "会员余额")
public class MemberStoreController extends BaseController {

    @Autowired
    private WxMsgUtil wxMsgUtil;
    @Autowired
    private SessionUtil sessionUtil;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberStoreLockUtils lockUtils;
    @Autowired
    private MemberStoreService storeService;
    @Autowired
    private MemberCapitalMeasurementService capitalMeasurementService;
    @Autowired
    private VerifyCodeUtil verifyCodeUtil;

    @ApiOperation("会员提币操作")
    @RequestLog("会员提币操作")
    @PostMapping("withdraw")
    public BaseResponse withdraw(@ApiParam @RequestBody @Validated MemberWithdrawReq withdrawReq) {
        LoginUserSession session = sessionUtil.getUser();
        if(session.getStoreFreezeStatus() == com.service.dao.enums.MemberEnums.StoreStatus.FROZEN.getCode()){
            throw new CommonException("账户资产已冻结，如有疑问请联系客服","account_assets_frozen");
        }

        //如果需要谷歌验证码
        if (!ObjectUtils.isEmpty(withdrawReq.getFaCode())) {
            //谷歌验证
            TwoFaReq twoFaReq = new TwoFaReq();
            twoFaReq.setFaCode(withdrawReq.getFaCode());
            memberService.checkTwoFa(twoFaReq);
        }else{
            //否则进行手机或邮箱验证
            verifyCodeUtil.verifyTextVerifyCode(session.getAccount(), withdrawReq.getVerifyCode(), SmsTypeEnum.WITHDRAW);
        }


        withdrawReq.setUserAccount(session.getAccount());
        withdrawReq.setMemberId(session.getUserId());
        storeService.doWithdraw(withdrawReq);
//        wxMsgUtil.sendFTWxMsg("提币申请","会员账号："+ withdrawReq.getMemberId()+"，提币数量：" + withdrawReq.getNum());
        return successBaseResponse();
    }

    @RequestLog("会员余额列表")
    @ApiOperation("会员余额列表")
    @PostMapping("list")
    public MultiResponse<MemberStorePageRep> list() {
        return successQueryMultiResponse(storeService.listMemberStore());
    }

    @ApiOperation("转账")
    @RequestLog("会员转账")
    @PostMapping("transfer-account")
    public BaseResponse transferAccount(@ApiParam @RequestBody @Validated TransferAccountReq accountReq) {
        LoginUserSession session = sessionUtil.getUser();
//        verifyCodeUtil.verifyTextVerifyCode(session.getAccount(), accountReq.getVerifyCode(), SmsTypeEnum.TRANSFER);
        if(session.getStoreFreezeStatus() == com.service.dao.enums.MemberEnums.StoreStatus.FROZEN.getCode()){
            throw new CommonException("账户资产已冻结，如有疑问请联系客服","account_assets_frozen");
        }
        Member targetMember = memberService.getMemberByAccount(accountReq.getUserAccount(), MemberEnums.Status.ACTIVE);
        if (ObjectUtils.isEmpty(targetMember)) {
            log.error("会员<{}>转账数量:{},转出账户:{},操作失败，不存在此会员", session.getUserId(), accountReq.getTransferNum(), accountReq.getUserAccount());
            throw new CommonException("暂无此会员", "not_found_user");
        }

        MemberStore sourceStore = storeService.getMemberStore(session.getUserId(), accountReq.getCoin().getName());
        MemberStore targetStore = storeService.getMemberStore(targetMember.getId(), accountReq.getCoin().getName());

        String[] lockKey = MemberStoreLockUtils.buildStoreKey(sourceStore, targetStore);
        RedissonRedLock redLock = lockUtils.getRedLock(lockKey);
        if (lockUtils.redLockTryLock(redLock)) {
            try {
                storeService.transferAccount(accountReq, session);
            } finally {
                redLock.unlock();
            }
        }
        return successQueryBaseResponse();
    }

    @ApiOperation("会员流水检测")
    @RequestLog("会员流水检测")
    @PostMapping("check-ja/{coin}")
    public BaseResponse checkJa(@PathVariable("coin") CoinsEnum coins) {
        LoginUserSession session = sessionUtil.getUser();
        capitalMeasurementService.checkJA(session.getUserId(), coins.getCode());
       return successQueryBaseResponse();
    }

}
